# -*- coding: utf-8 -*-
# @Date    : 2021/4/29
# @Author  : Maoxian
# 网上找到的第三方打码平台： 图鉴, 超人云, 联众等,价格对比:
# 图鉴: ttshitu.com   2厘/次
# 联众: jsdati.com    6.5厘/次
# 超人云: chaorendama.com  6厘/次


import base64
import time
import requests
from lxml import etree
from lianzhong import LianZhong

lz = LianZhong('xxxxxxxx', 'xxxxxxxxx')

login_url = 'https://so.gushiwen.cn/user/login.aspx'
code_url = 'https://so.gushiwen.cn/RandCode.ashx'
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/90.0.4430.85 Safari/537.36 Edg/90.0.818.49"
}


def login(email, pwd):
    rs = requests.Session()
    code_img = rs.get(code_url, headers=headers).content

    code_img = base64.b64encode(code_img).decode()  # 转换图片为base64
    lz_result = lz.upload(code_img)                 # 联众答题结果

    code = lz_result['data'].get('recognition')
    data = {
        "__VIEWSTATE": "lfY83CnGj/MvyaMOIu9zt/diHa6AOMUWtVoYXkbhczxoICxVNA9BDssZ4jru+r+ZRdYwZ2G79zpHjx2+QJvmNDCsrtAC/s+lFXgYrJeaBFrgyTUwumV7uUKRRDc=",
        "__VIEWSTATEGENERATOR": "C93BE1AE",
        "from": "http://so.gushiwen.cn/user/collect.aspx",
        "email": email,
        "pwd": pwd,
        "code": code,
        "denglu": "登录"
    }
    r = rs.post(login_url, headers=headers, data=data)
    return r


if __name__ == '__main__':
    is_login = False  # 判断是否登录
    while not is_login:
        response = login('xxxxxxxx@qq.com', 'xxxxxxxx')
        html = etree.HTML(response.text)
        try:
            # 成功登录后左上角有我的收藏
            if html.xpath('//div[@class="mainshoucang"]/span[1]/text()')[0] == "我的收藏":
                is_login = True
                print('登录成功')
            with open('index.html', 'w', encoding='utf8') as f:
                f.write(response.text)
        except IndexError:
            print('登录失败，正在重试...')
            time.sleep(1)
